<template>
  <a-cascader
    :field-names="{ label: 'name', value: 'code', children: 'children' }"
    :options="options"
    :value="nowCode"
    placeholder="请选择所在地"
    @change="onChange"
  />
</template>

<script>
  import { SysAreaCode, SysAreaSSCode } from '@/utils/areaCode'

  export default {
    name: 'WxAreaCode',
    data () {
      return {
        options: {},
        nowCode: []
      }
    },
    props: {
      areaCode: {
        type: String,
        required: false,
        default: ''
      },
      levels: {
        type: Number,
        required: false,
        default: 3
      }
    },
    watch: {
      areaCode (val) {
        if (this.levels === 3) {
          if (val !== null && val !== undefined) {
            this.nowCode = [val.substring(0, 2), val.substring(0, 4), val + '']
          }
        } else if (this.levels === 2) {
          if (val !== null && val !== undefined) {
            this.nowCode = [val.substring(0, 2), val.substring(0, 4)]
          }
        }
        console.log(this.nowCode)
      }
    },
    created () {
      if (this.levels === 3) {
        if (this.areaCode !== null && this.areaCode !== undefined) {
          this.nowCode = [this.areaCode.substring(0, 2), this.areaCode.substring(0, 4), this.areaCode + '']
        }
        this.options = SysAreaCode()
      } else if (this.levels === 2) {
        if (this.areaCode !== null && this.areaCode !== undefined) {
          this.nowCode = [this.areaCode.substring(0, 2), this.areaCode.substring(0, 4)]
        }
        this.options = SysAreaSSCode()
      }
    },
    methods: {
      onChange (value, selectedOptions) {
        const obj = {}
        if (this.levels === 3) {
          obj.code = value[2]
          obj.name = selectedOptions[0].name.concat(',') + selectedOptions[1].name.concat(',') + selectedOptions[2].name
        } else if (this.levels === 2) {
          obj.code = value[1]
          obj.name = selectedOptions[0].name.concat(',') + selectedOptions[1].name
        }
        this.$emit('ok', obj)
      }
    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>

<style scoped>

</style>
